<template>
  <el-card>
    <template #header>
      <div class="card-header">
        <span>员工列表</span>
        <el-button type="primary" style="float: right" @click="handleAdd">新增员工</el-button>
      </div>
    </template>

    <div class="search-bar">
      <el-input v-model="searchForm.keyword" placeholder="请输入姓名/部门" clearable @clear="fetchData" style="width: 200px" />
      <el-button type="primary" @click="fetchData">查询</el-button>
      <el-button @click="resetSearch">重置</el-button>
    </div>

    <el-table :data="userList" stripe :loading="loading" border fit>
      <el-table-column prop="id" label="ID" width="80" />
      <el-table-column prop="name" label="姓名" />
      <el-table-column prop="department" label="部门" />
      <el-table-column prop="position" label="职位" />
      <el-table-column prop="email" label="邮箱" />
      <el-table-column label="操作" width="200">
        <template #default="scope">
          <el-button type="text" size="small" @click="handleEdit(scope.row)">编辑</el-button>
          <el-button type="text" size="small" @click="handleDelete(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="currentPage"
      :page-sizes="[10, 20, 30]" :page-size="pageSize" layout="total, sizes, prev, pager, next, jumper" :total="total"
      style="margin-top: 20px" />
  </el-card>

  <!-- 编辑对话框 -->
  <el-dialog v-model="dialogVisible" :title="formData.id ? '编辑员工' : '新增员工'" @close="resetForm" destroy-on-close>
    <el-form :model="formData" :rules="formRules" ref="formRef" label-width="100px">
      <el-form-item label="姓名" prop="name">
        <el-input v-model="formData.name" />
      </el-form-item>
      <el-form-item label="部门" prop="department">
        <el-input v-model="formData.department" />
      </el-form-item>
      <el-form-item label="职位" prop="position">
        <el-input v-model="formData.position" />
      </el-form-item>
      <el-form-item label="邮箱" prop="email">
        <el-input v-model="formData.email" />
      </el-form-item>
      <el-form-item label="角色" prop="roleId">
        <el-select v-model="formData.roleId" placeholder="请选择角色">
          <el-option v-for="role in roleList" :key="role.id" :label="role.name" :value="role.id" />
        </el-select>
      </el-form-item>
      <el-form-item label="密码" prop="password" v-if="!formData.id">
        <el-input v-model="formData.password" type="password" />
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="dialogVisible = false">取消</el-button>
      <el-button type="primary" @click="saveUser">确定</el-button>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, reactive, onMounted, toRefs } from 'vue'
import { useUserStore } from '@/store/userStore'
import { ElMessage, ElMessageBox } from 'element-plus'
import request from '@/utils/request'

const userStore = useUserStore()
const { userList, loading } = toRefs(userStore)

// 分页和搜索
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)
const searchForm = reactive({
  keyword: ''
})

// 对话框
const dialogVisible = ref(false)
const formData = reactive({
  id: null,
  name: '',
  department: '',
  position: '',
  email: '',
  roleId: null,
  password: ''
})

const roleList = ref([])

const validateEmailUnique = async (rule, value, callback) => {
  if (!value) return callback()
  const users = await userStore.fetchUserList({})
  const exist = users.data.find(u => u.email === value && u.id !== formData.id)
  if (exist) {
    callback(new Error('邮箱已存在'))
  } else {
    callback()
  }
}

const formRules = reactive({
  name: [
    { required: true, message: '请输入姓名', trigger: 'blur' }
  ],
  department: [
    { required: true, message: '请输入部门', trigger: 'blur' }
  ],
  email: [
    { required: true, message: '请输入邮箱', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱格式', trigger: 'blur' },
    { validator: validateEmailUnique, trigger: 'blur' }
  ],
  roleId: [
    { required: true, message: '请选择角色', trigger: 'change' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' }
  ]
})

const formRef = ref(null)

// 获取数据
const fetchData = async () => {
  const params = {
    page: currentPage.value,
    pageSize: pageSize.value,
    keyword: searchForm.keyword
  }
  const res = await userStore.fetchUserList(params)
  total.value = res.total || 0
}

onMounted(() => {
  fetchData()
  fetchRoles()
})

const fetchRoles = async () => {
  roleList.value = await request.get('/roles')
}

// 分页事件
const handleSizeChange = (newSize) => {
  pageSize.value = newSize
  fetchData()
}

const handleCurrentChange = (newPage) => {
  currentPage.value = newPage
  fetchData()
}

// 搜索重置
const resetSearch = () => {
  searchForm.keyword = ''
  fetchData()
}

// 新增/编辑
const handleAdd = () => {
  resetForm()
  formData.id = null
  formData.name = ''
  formData.department = ''
  formData.position = ''
  formData.email = ''
  formData.roleId = null
  formData.password = ''
  dialogVisible.value = true
}

const handleEdit = (row) => {
  formData.id = row.id
  formData.name = row.name
  formData.department = row.department
  formData.position = row.position
  formData.email = row.email
  formData.roleId = row.roleId
  formData.password = '' // 编辑时密码可选填
  dialogVisible.value = true
}

// 保存用户
const saveUser = () => {
  formRef.value.validate(async (valid) => {
    if (valid) {
      try {
        if (formData.id) {
          await userStore.updateUser(formData)
          dialogVisible.value = false
          fetchData()
          ElMessage.success('更新成功')
        } else {
          await userStore.addUser(formData)
          // 新增后跳转到最后一页
          const res = await userStore.fetchUserList({})
          const totalUsers = res.total
          const lastPage = Math.ceil(totalUsers / pageSize.value)
          currentPage.value = lastPage
          await fetchData()
          dialogVisible.value = false
          ElMessage.success('添加成功')
        }
      } catch (error) {
        ElMessage.error(error.message || '操作失败')
      }
    }
  })
}

// 删除用户
const handleDelete = async (row) => {
  ElMessageBox.confirm(
    '确定要删除该员工吗？',
    '提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(async () => {
    try {
      await userStore.deleteUser(row.id)
      fetchData()
      ElMessage.success('删除成功')
    } catch (error) {
      ElMessage.error(error.message || '删除失败')
    }
  })
}

const resetForm = () => {
  formRef.value && formRef.value.resetFields()
}
</script>

<style scoped>
.search-bar {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
</style>